package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize,String name){
        //构造分页构造器
        Page<Dish> pageInfo = new Page(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(name != null,Dish::getName,name);
        //添加排序条件
        //执行查询
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //dishService.page(pageInfo,queryWrapper);
        dishService.page(pageInfo, queryWrapper);
        //进行对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId(); //分类ID
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    @PostMapping
    public R<String> save(@RequestBody  DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveOrUpdateWithFlavor(dishDto);

        return  R.success("新增菜品成功");
    }

    @GetMapping("/{dishId}")
    public R<Dish> backRow(@PathVariable Long dishId){
        //log.info("dishId:{}",dishId);
        DishDto dishDto = new DishDto();
        //获取dish
        Dish dishRow = dishService.getById(dishId);
        //获取dishFlavor
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(dishId != null,DishFlavor::getDishId,dishId);
        //赋值
        BeanUtils.copyProperties(dishRow,dishDto);
        dishDto.setFlavors(dishFlavorService.list(dishFlavorLambdaQueryWrapper));



        return R.success(dishDto);
    }
    //更新菜品
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto){
        dishService.saveOrUpdateWithFlavor(dishDto);

        return R.success("修改成功");
    }


    /**
     * 停售设置
     * 请求网址: http://localhost:8080/dish/status/0?ids=1631134435325894658
     * 请求方法: POST
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable int status,Long ids){

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getId,ids);
        Dish dish = new Dish();
        dish.setStatus(status);
        boolean update = dishService.update(dish,dishLambdaQueryWrapper);
        if (update == true)return R.success("成功喽");
        return R.error("失败喽");
    }

    /**
     * 删除某一个dish
     * 请求网址: http://localhost:8080/dish?ids=1631986537468112897
     * 请求方法: DELETE
     */
    @DeleteMapping()
    public R<String> deleteDish(@RequestParam("ids") List<Long> ids){
        //log.info("listIds:{}",ids.toString());
        //dishService.deleteDishById(ids);
        return R.success("删除成功喽");
    }

    /**
     * 根据条件查询对应的菜品数据
     * 请求网址: http://localhost:8080/dish/list?categoryId=1397844263642378242
     * 请求方法: GET
     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        //构造查询条件
//        log.info("categoryid:{}",dish.getCategoryId());
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }


}